package com.lxf.clouduser.service.impl;

import com.lxf.clouduser.service.CaptchaService;
import com.lxf.clouduser.utils.CaptchaUtils;
import liquibase.pro.packaged.E;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 罗兴发
 * @data 2025/9/25 10:54
 * @description：图片验证码-业务实现类(用于处理图片验证码的生成和验证)
 */
@Service
@Slf4j
public class CaptchaServiceImpl implements CaptchaService {
    private static int MAX_INA = 300;

    /**
     * 生成验证码，并将验证码存储到session服务器中
     * @return base64图片
     */
    @Override
    public String generateCaptcha() {
        try {
            CaptchaUtils.MathExpression mathExpression = CaptchaUtils.generateMathExpression();
            String imgBase64 = CaptchaUtils.generateCaptchaImage(mathExpression.getExpression());

            // 获取session并存储答案
            ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
            HttpSession session = sra.getRequest().getSession();
            session.setAttribute("captchaAnswer",mathExpression.getResult());
            session.setMaxInactiveInterval(MAX_INA);//设置有效期
            return imgBase64;
        }catch (Exception e){
            e.printStackTrace();
            log.info(e.getMessage());
        }
        return null;
    }

    /**
     * 验证用户输入的答案是否正确
     * @param userAnswer 用户输入的答案
     * @return 是否正确
     */
    @Override
    public boolean validateCaptcha(String userAnswer) {
        try {
            int answer = Integer.parseInt(userAnswer);

            // 获取session中的答案
            // 获取session并存储答案
            ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
            HttpSession session = sra.getRequest().getSession();
            Integer captchaAnswer = (Integer)session.getAttribute("captchaAnswer");

            log.info("用户输入的答案：{}",answer);
            log.info("正确答案：{}",captchaAnswer);
            log.info("Session ID：{}",session.getId());

            // 判断用户输入的答案是否正确
            if (null!=captchaAnswer&&answer==captchaAnswer){
                //验证成功后，删除session中的正确答案
                session.removeAttribute("captchaAnswer");
                log.info("验证码验证成功！");
                return true;
            }else {
                log.info("验证码验证失败！");
                return false;
            }
        }catch (NumberFormatException e){
            e.printStackTrace();
            log.info("数字转换异常！");
            return false;
        }
    }
}
